package com.xnyzc.lhy.common.component.amap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.entity.GouldHistoryGps;
import com.xnyzc.lhy.common.entity.GouldLYResult;
import com.xnyzc.lhy.common.entity.GouldResult;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.gould.EGould;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.GpsUtil;
import com.xnyzc.lhy.common.util.RandomUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: huxuekuo
 * @Date: 2019-07-29 15:49
 * @Description: 封装高德地图
 */
@Slf4j
@Data
@Component
public class GouldMapUtils {

    /**
     * 高德 Web API
     */
    public static String webKey;

    /**
     * 高德 Web API 备用1
     */
    public static String webKeyBackupOne;

    /**
     * 高德 Web API 备用2
     */
    public static String webKeyBackupTwo;

    public static String webKeyBackupThree;

    public static String webKeyBackupFour;

    public static String webKeyBackupFive;

    public static String webKeyBackupSix;

    public static String webKeyBackupSeven;

    public static String webKeyBackupEight;

    public static String webKeyBackupNine;
    /**
     * 上传点位
     * 轨迹点上传（单点、批量）
     */
    private static final String UPLOADTRACK = "https://tsapi.amap.com/v1/track/point/upload";

    @Value("${global.amap.webKey}")
    public void setWebKey(String amapWebKey) {
        webKey = amapWebKey;
    }

    @Value("${global.amap.webKeyBackupOne}")
    public void setMapWebKeyBackupOne(String mapWebKeyBackupOne) {
        webKeyBackupOne = mapWebKeyBackupOne;
    }

    @Value("${global.amap.webKeyBackupTwo}")
    public void setMapWebKeyBackupTwo(String mapWebKeyBackupTwo) {
        webKeyBackupTwo = mapWebKeyBackupTwo;
    }

    @Value("${global.amap.webKeyBackupThree}")
    public void setMapWebKeyBackupThree(String mapWebKeyBackupThree) {
        webKeyBackupThree = mapWebKeyBackupThree;
    }

    @Value("${global.amap.webKeyBackupFour}")
    public void setMapWebKeyBackupFour(String mapWebKeyBackupFour) {
        webKeyBackupFour = mapWebKeyBackupFour;
    }

    @Value("${global.amap.webKeyBackupFive}")
    public void setMapWebKeyBackupFive(String mapWebKeyBackupFive) {
        webKeyBackupFive = mapWebKeyBackupFive;
    }

    @Value("${global.amap.webKeyBackupSix}")
    public void setMapWebKeyBackupSix(String mapWebKeyBackupSix) {
        webKeyBackupSix = mapWebKeyBackupSix;
    }

    @Value("${global.amap.webKeyBackupSeven}")
    public void setMapWebKeyBackupSeven(String mapWebKeyBackupSeven) {
        webKeyBackupSeven = mapWebKeyBackupSeven;
    }

    @Value("${global.amap.webKeyBackupEight}")
    public void setMapWebKeyBackupEight(String mapWebKeyBackupEight) {
        webKeyBackupEight = mapWebKeyBackupEight;
    }

    @Value("${global.amap.webKeyBackupNine}")
    public void setMapWebKeyBackupNine(String mapWebKeyBackupNine) {
        webKeyBackupNine = mapWebKeyBackupNine;
    }

    /**
     * 测距接口
     */
    private static final String DISTANCE_URL = "http://restapi.amap.com/v3/distance?";

    private static final String TSAPI = "https://tsapi.amap.com/v1/track/terminal/trsearch?";


    /**
     * 测距接口--起点参数
     */
    private static final String ORIGINS = "origins=";

    /**
     * 测距接口--终点参数
     */
    private static final String DESTINATION = "destination=";

    /**
     * 字符串拼接
     */
    private static final String AND = "&";

    private static final String PATH_URL = "http://restapi.amap.com/v3/direction/driving?";
    /**
     * 地理/逆地理编码
     */
    private static final String AREA_URL = "https://restapi.amap.com/v3/geocode/regeo?";

    private static final String SERVICE_URL = "https://tsapi.amap.com/v1/track/service/add?";
    private static final String TERMINAL_URL = "https://tsapi.amap.com/v1/track/terminal/add?";
    private static final String TRACK_URL = "https://tsapi.amap.com/v1/track/trace/add?";
    private static final String TRACK_UPLOAD = "https://tsapi.amap.com/v1/track/point/upload?";


    public static GouldHistoryGps historyGps(Long sid, Long trid, Long tid,  int page) {
        StringBuffer sb = new StringBuffer();
        sb.append(TSAPI);
        sb.append("key=" + webKey);
        sb.append("&sid=" + sid);
        sb.append("&trid=" + trid);
        sb.append("&tid=" + tid);
        sb.append("&correction=denoise=0,mapmatch=1,attribute=0,threshold=0,mode=driving");
        sb.append("&page=" + page);
        sb.append("&pagesize=999");
        HttpGet get = new HttpGet(sb.toString());
        HttpClient httpClient = HttpClientBuilder.create().build();
        try {
            //发送请求
            HttpResponse execute = httpClient.execute(get);
            if (responseStatus(execute.getStatusLine())) {
                HttpEntity entity = execute.getEntity();
                StringBuilder strJson = getJson(entity);
                //如果内容不为空,将内存转换为JSON返回
                if (StringUtils.isNotEmpty(strJson.toString())) {
                    return JSON.parseObject(strJson.toString(), GouldHistoryGps.class);
                }
            }
        } catch (IOException e) {
            throw PangException.create(EErrorCode.c500);
        }
        throw PangException.create(EErrorCode.apiRstError);
    }

    public static StringBuilder getJson(HttpEntity entity) {
        //获取返回内容,将返回内容转换为JSON数据
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(entity.getContent());
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            StringBuilder strJson = new StringBuilder();
            //从文件中按字节读取内容，到文件尾部时read方法将返回-1
            while ((bytesRead = bis.read(buffer)) != -1) {
                //将读取的字节转为字符串对象
                strJson.append(new String(buffer, 0, bytesRead));
            }
            return strJson;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 测两个点位之间的距离
     *
     * @param startPoint 起点例如(116.413731,39.979324)
     * @param endPoint   终点(116.413731,39.979324)
     * @return
     */
    public static GouldResult getDistance(String startPoint, String endPoint) {
        GouldResult gouldResult = null;
        if (GpsUtil.checkItudePoint(startPoint) && GpsUtil.checkItudePoint(endPoint)) {
            //拼接参数
            StringBuffer stringBuffer = new StringBuffer(DISTANCE_URL);
            stringBuffer.append("key=" + webKey);
            stringBuffer.append(AND + ORIGINS + startPoint);
            stringBuffer.append(AND + DESTINATION + endPoint);
            HttpGet get = new HttpGet(stringBuffer.toString());
            gouldResult = readContent(get);

        }
        return gouldResult;
    }

    /**
     * 同城 19路径规划
     *
     * @param startPoint
     * @param endPoint
     * @return
     */
    public static GouldResult getPath(String startPoint, String endPoint) {
        //设置参数,详见高德接口文档
        StringBuilder stringBuilder = new StringBuilder(PATH_URL);
        stringBuilder.append("key=" + getRandomWebKey());
        stringBuilder.append("&origin=" + startPoint);
        stringBuilder.append("&destination=" + endPoint);
        stringBuilder.append("&originid=");
        stringBuilder.append("&destinationid=");
        stringBuilder.append("&extensions=all");
        stringBuilder.append("&strategy=19");//10躲避拥堵，路程较短，尽量缩短时间 19高速优先
        stringBuilder.append("&waypoints=");
        stringBuilder.append("&avoidpolygons=");
        stringBuilder.append("&avoidroad=");
        HttpGet get = new HttpGet(stringBuilder.toString());
        GouldResult gouldResult = readContent(get);
        return gouldResult;
    }

    /**
     * 携程 10路径规划
     *
     * @param strategy   线路策略值
     * @param startPoint
     * @param endPoint
     * @return
     */
    public static GouldResult getPathXC(int strategy, String startPoint, String endPoint) {
        //设置参数,详见高德接口文档
        StringBuilder stringBuilder = new StringBuilder(PATH_URL);
        stringBuilder.append("key=" + getRandomWebKey());
        stringBuilder.append("&origin=" + startPoint);
        stringBuilder.append("&destination=" + endPoint);
        stringBuilder.append("&originid=");
        stringBuilder.append("&destinationid=");
        stringBuilder.append("&extensions=all");
        stringBuilder.append("&strategy=" + strategy);//10躲避拥堵，路程较短，尽量缩短时间 19高速优先
        stringBuilder.append("&waypoints=");
        stringBuilder.append("&avoidpolygons=");
        stringBuilder.append("&avoidroad=");
        HttpGet get = new HttpGet(stringBuilder.toString());
        GouldResult gouldResult = readContent(get);
        return gouldResult;
    }

    /**
     * 路径规划
     *
     * @param startPoint
     * @param endPoint
     * @return
     */
    public static GouldResult getPathTactless(String startPoint, String endPoint) {
        //设置参数,详见高德接口文档
        StringBuilder stringBuilder = new StringBuilder(PATH_URL);
        stringBuilder.append("key=" + getRandomWebKey());
        stringBuilder.append("&origin=" + startPoint);
        stringBuilder.append("&destination=" + endPoint);
        stringBuilder.append("&originid=");
        stringBuilder.append("&destinationid=");
        stringBuilder.append("&extensions=base");
        stringBuilder.append("&strategy=2");
        stringBuilder.append("&waypoints=");
        stringBuilder.append("&avoidpolygons=");
        stringBuilder.append("&avoidroad=");
        HttpGet get = new HttpGet(stringBuilder.toString());
        GouldResult gouldResult = readContent(get);
        return gouldResult;
    }

    /**
     * 获取请求状态
     *
     * @param status
     * @return
     */
    private static boolean responseStatus(StatusLine status) {
        return status.getStatusCode() == 200 ? true : false;
    }

    /**
     * 获取请求内容
     *
     * @param get 内容流
     * @return
     */
    private static GouldResult readContent(HttpGet get) {
        log.info("httpClient请求：{}", get.getURI());
        log.info("-------进入HTTP请求方法(验证是否部署成功)-------");
        long startTime = System.currentTimeMillis();
        HttpClient client = HttpClientPool.getClient();
        try (CloseableHttpResponse execute = (CloseableHttpResponse) client.execute(get)) {
            // 处理响应内容....
            if (responseStatus(execute.getStatusLine())) {
                HttpEntity entity = execute.getEntity();
                StringBuilder strJson = getJson(entity);
                //如果内容不为空,将内存转换为JSON返回
                if (StringUtils.isNotEmpty(strJson.toString())) {
                    GouldResult gouldResult1 = JSON.parseObject(strJson.toString(), GouldResult.class);
                    log.info("httpClient 请求耗时：{}", System.currentTimeMillis() - startTime);
                    return gouldResult1;
                }
            }
        } catch (ClientProtocolException e) {
            log.error("httpClient请求异常：{}", e);
            throw PangException.create(EErrorCode.c500);
        } catch (IOException e) {
            log.error("httpClient请求异常：{}", e);
            throw PangException.create(EErrorCode.c500);
        }
        throw PangException.create(EErrorCode.apiRstError);
    }

    /**
     * 同城 策略19，去其中价格最优的
     * 包含预估轨迹信息
     *
     * @return
     */
    public static GouldResult.RouteBean getStrategy(String startPoint, String endPoint) {
        //开多线程执行路径规划，高度逆地理编码
        final CountDownLatch latch = new CountDownLatch(2);
        Double slon = Double.parseDouble(startPoint.split(",")[0]);
        Double slat = Double.parseDouble(startPoint.split(",")[1]);
        Double dlon = Double.parseDouble(endPoint.split(",")[0]);
        Double dlat = Double.parseDouble(endPoint.split(",")[1]);
        GouldResult.RouteBean route = getPath(startPoint, endPoint).getRoute();
        //第一个子线程执行
        ExecutorService es1 = Executors.newSingleThreadExecutor();
        es1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //调用高德接口
                    System.out.println("子线程：" + Thread.currentThread().getName() + "执行起点逆地理");
                    GouldResult sRe = GouldMapUtils.verificationEmbargoArea(slon + "", slat + "");
                    String sAdCode = sRe.getRegeocode().getAddressComponent().getAdcode();
                    route.setSAcode(sAdCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        es1.shutdown();
        //第二个子线程执行
        ExecutorService es2 = Executors.newSingleThreadExecutor();
        es2.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("子线程：" + Thread.currentThread().getName() + "执行终点逆地理");
                    GouldResult eRe = GouldMapUtils.verificationEmbargoArea(dlon + "", dlat + "");
                    String eAdCode = eRe.getRegeocode().getAddressComponent().getAdcode();
                    route.setEAcode(eAdCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        es2.shutdown();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return route;
    }

    public static GouldResult getAreaInfo(String lon, String lat) {
        GouldResult areaInfo = verificationEmbargoArea(lon, lat);

        return areaInfo;
    }

    /**
     * 携程 策略10，去其中价格最优的
     * 包含预估轨迹信息
     *
     * @return
     */
    public static GouldResult.RouteBean getStrategyXC(int strategy, String startPoint, String endPoint) {
        //开多线程执行路径规划，高度逆地理编码
        final CountDownLatch latch = new CountDownLatch(2);
        Double slon = Double.parseDouble(startPoint.split(",")[0]);
        Double slat = Double.parseDouble(startPoint.split(",")[1]);
        Double dlon = Double.parseDouble(endPoint.split(",")[0]);
        Double dlat = Double.parseDouble(endPoint.split(",")[1]);
        GouldResult.RouteBean route = getPathXC(strategy, startPoint, endPoint).getRoute();
        //第一个子线程执行
        ExecutorService es1 = Executors.newSingleThreadExecutor();
        es1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //调用高德接口
                    System.out.println("子线程：" + Thread.currentThread().getName() + "执行起点逆地理");
                    GouldResult sRe = GouldMapUtils.verificationEmbargoArea(slon + "", slat + "");
                    String sAdCode = sRe.getRegeocode().getAddressComponent().getAdcode();
                    route.setSAcode(sAdCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        es1.shutdown();
        //第二个子线程执行
        ExecutorService es2 = Executors.newSingleThreadExecutor();
        es2.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("子线程：" + Thread.currentThread().getName() + "执行终点逆地理");
                    GouldResult eRe = GouldMapUtils.verificationEmbargoArea(dlon + "", dlat + "");
                    String eAdCode = eRe.getRegeocode().getAddressComponent().getAdcode();
                    route.setEAcode(eAdCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        es2.shutdown();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return route;
    }

    /**
     * 此方法不用，保存之前的方法数据
     * 策略10，去其中价格最优的
     * 包含预估轨迹信息
     *
     * @return
     */
    public static List<Map<String, String>> getStrategy2(String startPoint, String endPoint) {
        List<Map<String, String>> list = new ArrayList<>();
        GouldResult.RouteBean route = getPath(startPoint, endPoint).getRoute();
        List<GouldResult.RouteBean.PathsBean> paths = route.getPaths();
        int size = paths.size();
        log.info("我是驾车路径规划策略10，共查处{}条记录", size);
        for (int i = 0; i < size; i++) {
            Map<String, String> result = new HashMap<>(6);
            GouldResult.RouteBean.PathsBean path = paths.get(i);
            //设置里程,和时间
            result.put(EGould.gouldDistance.getValue(), path.getDistance());
            result.put(EGould.gouldDuration.getValue(), path.getDuration());
            List<GouldResult.RouteBean.PathsBean.StepsBean> steps = path.getSteps();
            StringBuffer stringBuffer = new StringBuffer();
            for (GouldResult.RouteBean.PathsBean.StepsBean stepsBean : steps) {
                stringBuffer.append(stepsBean.getPolyline());
                stringBuffer.append(";");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            result.put(EGould.gouldPolyline.getValue(), stringBuffer.toString());
            list.add(result);
        }
        // 交给mq把预估点位信息存起来
        return list;
    }

    /**
     * 获取速度最快的公里数与时间段
     * 不包含预估轨迹信息
     *
     * @return
     */
    public static Map<String, String> getStrategyTactless(String startPoint, String endPoint) {
        Map<String, String> result = new HashMap<>();
        GouldResult.RouteBean route = getPathTactless(startPoint, endPoint).getRoute();
        List<GouldResult.RouteBean.PathsBean> paths = route.getPaths();
        int size = paths.size();
        for (int i = 0; i < size; i++) {
            GouldResult.RouteBean.PathsBean path = paths.get(i);
            //设置里程,和时间
            result.put(EGould.gouldDistance.getValue(), path.getDistance());
            result.put(EGould.gouldDuration.getValue(), path.getDuration());
            return result;
        }
        // 交给mq把预估点位信息存起来
        return result;
    }

    public static double getDistance(String startLng, String startLat, String endLng, String endLat) {
        //判断轨迹是否为空
        if (CheckUtil.strIsEmpty(startLng, startLat, endLng, endLat)) {
            throw PangException.create(EErrorCode.gpsError);
        }
        Map<String, String> strategy = getStrategyTactless(startLng + "," + startLat, endLng + "," + endLat);
        Integer integer = Integer.valueOf(strategy.get(EGould.gouldDistance.getValue()));
        return BigDecimal.valueOf(Math.rint(Double.valueOf(integer / 100) / 10)).setScale(1, BigDecimal.ROUND_HALF_DOWN).doubleValue();
    }

    public static HashMap<String, String> getDistanceAndDuration(String startPoint, String endPoint) {
        HashMap<String, String> result = new HashMap<>();
        Map<String, String> strategy = getStrategyTactless(startPoint, endPoint);
        //转换为KM
        result.put(EGould.gouldDistance.getValue(), new BigDecimal(Math.rint(Double.valueOf(Integer.valueOf(strategy.get(EGould.gouldDistance.getValue())) / 100) / 10)).setScale(1, BigDecimal.ROUND_HALF_DOWN) + MessageConstant.KILOMETRE);
        result.put(EGould.gouldDuration.getValue(), new BigDecimal(Math.rint(Double.valueOf(strategy.get(EGould.gouldDuration.getValue())) / 60)).setScale(1, BigDecimal.ROUND_HALF_DOWN) + MessageConstant.MINUTES);
        return result;
    }

    /**
     * 随机获取高德web key
     *
     * @return
     */
    public static String getRandomWebKey() {
        String key = webKey;
        Integer number = 0;
        try {
            number = Integer.valueOf(RandomUtil.getRandomNumberStr(1));
        } catch (Exception e) {
            log.error("随机获取高德web key 异常：{}", e);
        }
        switch (number) {
            case 1:
                key = webKeyBackupOne;
                break;
            case 2:
                key = webKeyBackupTwo;
                break;
            case 3:
                key = webKeyBackupThree;
                break;
            case 4:
                key = webKeyBackupFour;
                break;
            case 5:
                key = webKeyBackupFive;
                break;
            case 6:
                key = webKeyBackupSix;
                break;
            case 7:
                key = webKeyBackupSeven;
                break;
            case 8:
                key = webKeyBackupEight;
                break;
            case 9:
                key = webKeyBackupNine;
                break;
            default:
                key = webKey;
        }
        return key;
    }

    public static boolean uploadTrack(Long sid, Long tid, Long trid, List<Object> infoList) {
        // 设置请求参数
        StringBuffer sb = new StringBuffer();
        sb.append("key=" + "4815225edd855ffce09b96ec79b96f30");
        sb.append("&sid=" + sid);
        sb.append("&tid=" + tid);
        sb.append("&trid=" + trid);
        sb.append("&points=" + JSON.toJSONString(infoList));
        try {
            // POST请求设置参数
            HttpPost post = new HttpPost(UPLOADTRACK);
            // param参数，可以为"key1=value1&key2=value2"的一串字符串
            StringEntity stringEntity = new StringEntity(sb.toString());
            stringEntity.setContentType("application/x-www-form-urlencoded");
            post.setEntity(stringEntity);
            // 发送请求
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse httpResponse = httpClient.execute(post);
            String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
            System.out.println(result);
            if (CheckUtil.strIsNotEmpty(result)) {
                // 判断是否存在errcode并且是成功
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.containsKey("errcode") && jsonObject.getString("errcode").equals("10000")) {
                    return true;
                }
            }
            log.info("删除轨迹信息 服务ID:[{}],轨迹ID:[{}],终端ID:[{}] 返回信息:[{}]", sid, trid, tid, result);
        } catch (Exception e) {
            // 打印错误栈 ClassName.class
            log.error("", e);
        }
        return false;
    }

    /**
     * 判断禁行区域
     *
     * @param lon 经度  经度在前，纬度在后，经纬度间以“,”分割
     * @param lat 纬度
     * @return
     */
    public static GouldResult verificationEmbargoArea(String lon, String lat) {
        StringBuilder stringBuilder = new StringBuilder(AREA_URL);
        stringBuilder.append("key=" + getRandomWebKey());
        stringBuilder.append("&location=" + lon + "," + lat);
        stringBuilder.append("&extensions=" + "base");
        HttpGet get = new HttpGet(stringBuilder.toString());
        GouldResult gouldResult = readContent(get);
        return gouldResult;
    }


    /**
     * @param name 服务名称
     * @param desc 备注
     * @return
     */
    public static GouldLYResult registGouldLYService(String name, String desc) {
        StringBuilder stringBuilder = new StringBuilder(SERVICE_URL);
        stringBuilder.append("key=" + getRandomWebKey());
        stringBuilder.append("&name=" + name);
        stringBuilder.append("&desc=" + desc);
        HttpPost post = new HttpPost(stringBuilder.toString());
        GouldLYResult result = getResult(post);
        return result;
    }

    /**
     * @param sid  服务id
     * @param name 希望创建终端的名字，同一个service下不可出现名字相同的终端
     * @param desc 备注
     * @return
     */
    public static GouldLYResult registGouldLYTerminal(String sid, String name, String desc) {
        StringBuilder stringBuilder = new StringBuilder(TERMINAL_URL);
        stringBuilder.append("key=" + getRandomWebKey());
        stringBuilder.append("&sid=" + sid);
        stringBuilder.append("&name=" + name);
        stringBuilder.append("&desc=" + desc);
        HttpPost post = new HttpPost(stringBuilder.toString());
        GouldLYResult result = getResult(post);
        return result;
    }

    /**
     * @param sid    服务id
     * @param tid    终端id
     * @param trname 轨迹名称
     * @return
     */
    public static GouldLYResult registTrace(String sid, String tid, String trname) {
        StringBuilder stringBuilder = new StringBuilder(TRACK_URL);
        stringBuilder.append("key=" + getRandomWebKey());
        stringBuilder.append("&sid=" + sid);
        stringBuilder.append("&tid=" + tid);
        stringBuilder.append("&trname=" + trname);
        HttpPost post = new HttpPost(stringBuilder.toString());
        GouldLYResult result = getResult(post);
        return result;
    }

    /**
     * @param sid    服务id
     * @param tid    终端id
     * @param trid   轨迹id
     * @param infoList 轨迹点
     * @return
     */
    public static Boolean uploadTrackNew(Long sid, Long tid, Long trid, String infoList) {
        // 设置请求参数
        StringBuffer sb = new StringBuffer();
        sb.append("key=" +  getRandomWebKey());
        sb.append("&sid=" + sid);
        sb.append("&tid=" + tid);
        sb.append("&trid=" + trid);
        sb.append("&points=" + infoList);
        try {
            // POST请求设置参数
            HttpPost post = new HttpPost(UPLOADTRACK);
            // param参数，可以为"key1=value1&key2=value2"的一串字符串
            StringEntity stringEntity = new StringEntity(sb.toString());
            stringEntity.setContentType("application/x-www-form-urlencoded");
            post.setEntity(stringEntity);
            // 发送请求
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse httpResponse = httpClient.execute(post);
            String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
            if (CheckUtil.strIsNotEmpty(result)) {
                // 判断是否存在errcode并且是成功
                GouldLYResult jsonObject = JSON.parseObject(result,GouldLYResult.class);
                if ( jsonObject.getErrcode().equals("10000")) {
                    return true;
                }
            }
            log.info("删除轨迹信息 服务ID:[{}],轨迹ID:[{}],终端ID:[{}] 返回信息:[{}]", sid, trid, tid, result);
        } catch (Exception e) {
            // 打印错误栈 ClassName.class
            log.error("", e);
        }
        return false;
    }

    public String getTaskCreateJsonReq(JSONObject json) {
        StringBuffer req = new StringBuffer();
        try {
            String encode = URLEncoder.encode(json.toJSONString(), "UTF-8");
            req.append("?data=" + encode);
        } catch (UnsupportedEncodingException e) {
            req.append("?data=");
            log.error("TaskReqUtils.getTaskCreateReq [JSONObject]: " + json.toString());
        }
        log.info("TaskReqUtils.getTaskCreateJsonReq [JSONObject]: " + json.toString());
        return req.toString();
    }

    public static GouldLYResult getResult(HttpPost post) {
        long startTime = System.currentTimeMillis();
        HttpClient client = HttpClientPool.getClient();
        try (CloseableHttpResponse execute = (CloseableHttpResponse) client.execute(post)) {
            // 处理响应内容....
            if (responseStatus(execute.getStatusLine())) {
                HttpEntity entity = execute.getEntity();
                StringBuilder strJson = getJson(entity);
                //如果内容不为空,将内存转换为JSON返回
                if (StringUtils.isNotEmpty(strJson.toString())) {
                    GouldLYResult gouldLYResult = JSON.parseObject(strJson.toString(), GouldLYResult.class);
                    log.info("httpClient 请求耗时：{}", System.currentTimeMillis() - startTime);
                    return gouldLYResult;
                }
            }
        } catch (ClientProtocolException e) {
            log.error("httpClient请求异常：{}", e);
            throw PangException.create(EErrorCode.c500);
        } catch (IOException e) {
            log.error("httpClient请求异常：{}", e);
            throw PangException.create(EErrorCode.c500);
        }
        throw PangException.create(EErrorCode.apiRstError);
    }
}
